import CryptoJS from "crypto-js";

import config from '../config'


// 加密Token
let encryptToken = token => {
  let srcs = CryptoJS.enc.Utf8.parse(token);
  let encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(config.tokenEncryptKey), { iv: CryptoJS.enc.Utf8.parse(config.tokenEncryptIv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.ciphertext.toString().toUpperCase();
};


// 解密Token
let decryptToken = encryptedToken => {
  let encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedToken);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(srcs, CryptoJS.enc.Utf8.parse(config.tokenEncryptKey), { iv: CryptoJS.enc.Utf8.parse(config.tokenEncryptIv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
};


// 加密token后保存到localstorage
export let saveToken = token => {
  let encryptedToken = encryptToken(token);
  localStorage.setItem('token',encryptedToken);
};


// 从token中获取基本的用户信息存入sessionstorage
export let saveUserinfo = token => {
  let payLoad = getPayload(token);
  sessionStorage.setItem('aaa','bbb');
  sessionStorage.setItem('userInfo',JSON.stringify(payLoad));
};

// 从sessionStorage中获取用户信息
export let getUserinfo = () =>{
  return JSON.parse(sessionStorage.getItem('userInfo'))
};


// 从localStorage中获取token并解密
export let getLocalToken = () => {
  let encryptedToken = localStorage.getItem('token');
  if(encryptedToken){
    return decryptToken(encryptedToken);
  }
  else{
    return '';    // 如果localstorage中没有token，则返回空
  }
};


// 从token中获取payload
export let getPayload = (token)=>{
  let basedPayload = token.split('.')[1];
  let payload = Buffer.from(basedPayload, 'base64');
  return JSON.parse(payload.toString());
};




export default {
  saveToken,getLocalToken
}
